package edu.ncsu.csc.camera.com;

// for SPOT
import com.sun.squawk.util.StringTokenizer;
// for PC
//import java.util.StringTokenizer;


/**
 * A CMUCameraPacket that is an abstraction of the Type H packet.
 * An H packet is a Histogram that can contain 28, 14 or 7 bins
 * It is returned from the GH call (Get Histogram)
 * @author Richard Pospesel
 * @author Douglas McClusky
 */

public class HPacket extends CMUCameraPacket
{
	private byte[] bins;

    /**
     * Constructs an HPacket from the toByteArray method
	 * @param bins
     */
	 
	public HPacket (byte[] bins)
	{
		init(bins);
	}
	
	/**
     * Constructs an HPacket from the String output of the CMUCam2
     * Constructor, expects a String in the following format:
	 * H bin0 bin1 bin2 ... binN
     * @param str
     * @throws java.lang.IllegalArgumentException
     */
    
    public HPacket (String str) throws IllegalArgumentException
	{
		StringTokenizer st = new StringTokenizer(str, " \r");
		int _size = st.countTokens() - 1;	// number of bins
		if(st.nextToken().equals("H"))
		{
			byte[] _bins = new byte[_size];
			for(int k = 0; k < _size; k++)
			{
				_bins[k] = (byte)Integer.parseInt(st.nextToken());
			}
			init(_bins);
		} else {
            throw new IllegalArgumentException("Malformed TPacket String");
        }
	}

	private void init(byte[] bins)
	{
		super.type = super.H_PACKET;
        this.bins = bins;
	}

	/**
     * Displays the HPacket as a String formatted as by the CMUCam2:
     * H bin0 bin1 bin2 ... binN
     * @return
     */
    public String toString()
	{
		String result = "H ";
		int size = bins.length;
		for(int k = 0; k < size; k++)
			result += (0xFF & (int)bins[k]) + " ";	// convert to unsigned byte
		return result;
	}

    /**
     * Getter for the bins array contained in this HPacket
     * @return
     */
    public byte[] getBins() {
        return bins;
    }

    /**
     * A byte array representation of this HPacket for communication purposes
     * @return
     */
    public byte[] toByteArray() {
        return bins;
    }
}